package com.ithaipeng.redanttakeaway.filter;

import com.alibaba.fastjson.JSON;
import com.ithaipeng.redanttakeaway.tools.BaseContext;
import com.ithaipeng.redanttakeaway.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 自定义过滤器
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //定义一个工具类
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //先把这些强转成 http..
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //自定义不过滤的请求
        String[] urls={"/employee/login","/employee/login","/backend/**","/front/**","/common/**","/user/sendMsg","/user/login"};
        //获取当前url
        String requestURI= request.getRequestURI();
        //1 如果不需要处理那么直接放行
        if(check(urls,requestURI)){
            log.info("本次请求不过滤:{}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //2 如果登录状态，那么直接放行
        if(request.getSession().getAttribute("empId")!=null){
            //不等于null 代表已经登录，那么直接放行
            log.info("用户已经登录，用户id为:{}",request.getSession().getAttribute("empId"));
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("empId"));
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("userId")!=null){
            log.info("用户已经登录，用户id为:{}",request.getSession().getAttribute("userId"));
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("userId"));
            filterChain.doFilter(request,response);
            return;
        }
        // 3 要是没有登录，那么则返回登录界面
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }
    //定义一个匹配方法,返回值一定是布尔类型的
    public boolean check(String[] urls,String requestURI){
        for (String url:
             urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
